// ==================== 修复后的动态效果JavaScript ==================== 
// 调整颜色配置以匹配黄色名片夹主题

// 鼠标轨迹粒子效果（调整为蓝色主题，保持名片的蓝色）
function initMouseTrailEffect() {
    let isMouseMoving = false;
    let mouseTimeout;
    
    document.addEventListener('mousemove', function(e) {
        isMouseMoving = true;
        clearTimeout(mouseTimeout);
        
        // 减少粒子生成频率，避免过度干扰
        if (Math.random() < 0.08) {
            createMouseParticle(e.pageX, e.pageY);
        }
        
        mouseTimeout = setTimeout(() => {
            isMouseMoving = false;
        }, 100);
    });
}

function createMouseParticle(x, y) {
    const particle = document.createElement('div');
    particle.className = 'particle';
    particle.style.left = (x - 2) + 'px';
    particle.style.top = (y - 2) + 'px';
    // 保持蓝色粒子（与名片主题一致）
    particle.style.background = `hsl(${220 + Math.random() * 40}, 70%, 60%)`;
    document.body.appendChild(particle);
    
    setTimeout(() => {
        if (particle.parentNode) {
            particle.remove();
        }
    }, 1000);
}

// 名片夹点击增强效果（黄色主题）
function enhanceFolderInteractions() {
    document.addEventListener('click', function(e) {
        const folder = e.target.closest('.card-folder');
        if (folder && !folder.classList.contains('card-folder-add')) {
            // 移除所有其他文件夹的active状态
            document.querySelectorAll('.card-folder').forEach(f => {
                f.classList.remove('active');
            });
            
            // 添加active状态到点击的文件夹
            folder.classList.add('active');
            
            // 创建黄色波纹效果
            createFolderRippleEffect(folder, e);
            
            // 添加轻微的震动效果
            folder.style.animation = 'none';
            setTimeout(() => {
                folder.style.animation = 'folderClick 0.3s ease';
            }, 10);
        }
    });
}

function createFolderRippleEffect(element, event) {
    const ripple = document.createElement('div');
    const rect = element.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    ripple.style.cssText = `
        position: absolute;
        width: 20px;
        height: 20px;
        border-radius: 50%;
        background: rgba(255, 235, 59, 0.6);
        left: ${x - 10}px;
        top: ${y - 10}px;
        transform: scale(0);
        animation: folderRipple 0.6s ease-out;
        pointer-events: none;
        z-index: 1000;
    `;
    
    element.style.position = 'relative';
    element.appendChild(ripple);
    
    setTimeout(() => {
        if (ripple.parentNode) {
            ripple.remove();
        }
    }, 600);
}

// 名片悬停增强效果（去除模糊，优化交互）
function enhanceCardInteractions() {
    const cards = document.querySelectorAll('.card-item');
    
    cards.forEach(card => {
        let hoverTimeout;
        
        card.addEventListener('mouseenter', function() {
            clearTimeout(hoverTimeout);
            
            // 清晰的悬停效果，无模糊
            this.style.boxShadow = `
                0 12px 32px rgba(59, 130, 246, 0.15),
                0 4px 12px rgba(0, 0, 0, 0.08)
            `;
            
            // 创建subtle的装饰效果
            createCardSubtleEffect(this);
        });
        
        card.addEventListener('mouseleave', function() {
            hoverTimeout = setTimeout(() => {
                this.style.boxShadow = '';
                // 移除装饰效果
                this.querySelectorAll('.card-decoration').forEach(s => s.remove());
            }, 200);
        });
        
        // 名片点击效果
        card.addEventListener('click', function(e) {
            if (!e.target.closest('.card-actions')) {
                createCardClickEffect(this, e);
            }
        });
    });
}

function createCardSubtleEffect(card) {
    // 移除现有的装饰
    card.querySelectorAll('.card-decoration').forEach(s => s.remove());
    
    // 创建1-2个subtle的装饰点
    const decorationCount = 1 + Math.floor(Math.random() * 2);
    
    for (let i = 0; i < decorationCount; i++) {
        setTimeout(() => {
            const decoration = document.createElement('div');
            decoration.className = 'card-decoration';
            decoration.style.cssText = `
                position: absolute;
                width: 3px;
                height: 3px;
                background: #60a5fa;
                border-radius: 50%;
                left: ${30 + Math.random() * 40}%;
                top: ${30 + Math.random() * 40}%;
                animation: subtleSparkle 1.2s ease-in-out;
                pointer-events: none;
                z-index: 5;
            `;
            card.appendChild(decoration);
            
            setTimeout(() => {
                if (decoration.parentNode) {
                    decoration.remove();
                }
            }, 1200);
        }, i * 300);
    }
}

function createCardClickEffect(card, event) {
    const rect = card.getBoundingClientRect();
    const x = event.clientX - rect.left;
    const y = event.clientY - rect.top;
    
    // 创建点击波纹（蓝色主题）
    const wave = document.createElement('div');
    wave.style.cssText = `
        position: absolute;
        width: 30px;
        height: 30px;
        border-radius: 50%;
        background: radial-gradient(circle, rgba(59, 130, 246, 0.25) 0%, transparent 70%);
        left: ${x - 15}px;
        top: ${y - 15}px;
        transform: scale(0);
        animation: cardWave 0.6s ease-out;
        pointer-events: none;
        z-index: 10;
    `;
    
    card.style.position = 'relative';
    card.appendChild(wave);
    
    setTimeout(() => {
        if (wave.parentNode) {
            wave.remove();
        }
    }, 600);
}

// 随机装饰闪烁效果（降低频率）
function initRandomSparkles() {
    setInterval(() => {
        if (Math.random() < 0.2) {
            createRandomSparkle();
        }
    }, 3000);
}

function createRandomSparkle() {
    const sparkle = document.createElement('div');
    sparkle.className = 'random-sparkle';
    sparkle.style.cssText = `
        position: fixed;
        width: 4px;
        height: 4px;
        background: hsl(${220 + Math.random() * 40}, 60%, 65%);
        border-radius: 50%;
        left: ${Math.random() * window.innerWidth}px;
        top: ${Math.random() * window.innerHeight}px;
        animation: subtleSparkle 1.8s ease-in-out;
        pointer-events: none;
        z-index: 1;
    `;
    document.body.appendChild(sparkle);
    
    setTimeout(() => {
        if (sparkle.parentNode) {
            sparkle.remove();
        }
    }, 1800);
}

// 页面加载动画序列
function initPageLoadAnimations() {
    // 为文件夹添加延迟动画
    const folders = document.querySelectorAll('.card-folder, .card-folder-add');
    folders.forEach((folder, index) => {
        folder.style.animationDelay = `${index * 0.08}s`;
        folder.classList.add('folder-entrance');
    });
    
    // 为名片添加延迟动画
    const cards = document.querySelectorAll('.card-item');
    cards.forEach((card, index) => {
        card.style.animationDelay = `${0.2 + index * 0.12}s`;
        card.classList.add('card-entrance');
    });
}

// 智能悬停检测（优化版）
function initSmartHover() {
    let lastMouseMove = Date.now();
    let isMouseStationary = false;
    
    document.addEventListener('mousemove', function() {
        lastMouseMove = Date.now();
        isMouseStationary = false;
    });
    
    // 检测鼠标是否静止
    setInterval(() => {
        if (Date.now() - lastMouseMove > 1500 && !isMouseStationary) {
            isMouseStationary = true;
            // 鼠标静止时的subtle效果
            createStationaryEffect();
        }
    }, 800);
}

function createStationaryEffect() {
    const elements = document.elementsFromPoint(mouseX || 0, mouseY || 0);
    const card = elements.find(el => el.classList.contains('card-item'));
    const folder = elements.find(el => el.classList.contains('card-folder'));
    
    if (card && !card.classList.contains('gentle-pulse')) {
        // 为悬停的名片添加subtle效果
        card.classList.add('gentle-pulse');
        card.style.animation = 'gentlePulse 2.5s ease-in-out infinite';
        setTimeout(() => {
            card.classList.remove('gentle-pulse');
            card.style.animation = '';
        }, 5000);
    }
}

// 跟踪鼠标位置
let mouseX = 0, mouseY = 0;
document.addEventListener('mousemove', function(e) {
    mouseX = e.clientX;
    mouseY = e.clientY;
});

// 添加新的CSS动画样式（通过JavaScript注入）
function injectDynamicStyles() {
    const style = document.createElement('style');
    style.textContent = `
        @keyframes folderClick {
            0% { transform: translateY(-4px) rotateX(8deg) scale(1.02); }
            50% { transform: translateY(-6px) rotateX(12deg) scale(1.04); }
            100% { transform: translateY(-4px) rotateX(8deg) scale(1.02); }
        }
        
        @keyframes folderRipple {
            to {
                transform: scale(3);
                opacity: 0;
            }
        }
        
        @keyframes cardWave {
            to {
                transform: scale(2.5);
                opacity: 0;
            }
        }
        
        @keyframes subtleSparkle {
            0%, 100% { 
                opacity: 0; 
                transform: scale(0) rotate(0deg); 
            }
            50% { 
                opacity: 0.8; 
                transform: scale(1) rotate(180deg); 
            }
        }
        
        @keyframes gentlePulse {
            0%, 100% { 
                box-shadow: 0 4px 20px rgba(59, 130, 246, 0.08);
                transform: translateY(0) scale(1);
            }
            50% { 
                box-shadow: 0 8px 28px rgba(59, 130, 246, 0.12);
                transform: translateY(-1px) scale(1.005);
            }
        }
        
        .folder-entrance {
            animation: folderEntrance 0.5s ease-out forwards;
        }
        
        .card-entrance {
            animation: cardEntranceDelayed 0.6s ease-out forwards;
        }
        
        @keyframes folderEntrance {
            from {
                opacity: 0;
                transform: translateY(15px) rotateX(-8deg) scale(0.9);
            }
            to {
                opacity: 1;
                transform: translateY(0) rotateX(0deg) scale(1);
            }
        }
        
        @keyframes cardEntranceDelayed {
            from {
                opacity: 0;
                transform: translateY(20px) scale(0.95);
            }
            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }
        
        /* 粒子效果样式 */
        .particle {
            position: fixed;
            width: 4px;
            height: 4px;
            background: #3b82f6;
            border-radius: 50%;
            pointer-events: none;
            z-index: 9999;
            animation: particleFade 1s linear forwards;
        }
        
        @keyframes particleFade {
            0% { opacity: 1; transform: scale(1); }
            100% { opacity: 0; transform: scale(0); }
        }
    `;
    document.head.appendChild(style);
}

// 性能优化的初始化函数
function initDynamicEffects() {
    // 检查设备性能和用户偏好
    const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const isLowEndDevice = navigator.hardwareConcurrency && navigator.hardwareConcurrency < 4;
    
    if (prefersReducedMotion) {
        console.log('Reduced motion mode enabled');
        return;
    }
    
    // 注入动态样式
    injectDynamicStyles();
    
    // 初始化各种效果（降低强度）
    if (!isLowEndDevice) {
        initMouseTrailEffect();
        initRandomSparkles();
    }
    
    enhanceFolderInteractions();
    enhanceCardInteractions();
    initPageLoadAnimations();
    initSmartHover();
    
    console.log('Dynamic effects initialized with reduced intensity');
}

// 清理函数
function cleanupDynamicEffects() {
    document.querySelectorAll('.particle, .card-decoration, .random-sparkle').forEach(el => {
        el.remove();
    });
}

window.addEventListener('beforeunload', cleanupDynamicEffects);

// 在页面加载完成后初始化动态效果
document.addEventListener('DOMContentLoaded', function() {
    setTimeout(initDynamicEffects, 300);
});

// 导出函数供其他脚本使用
window.dynamicEffects = {
    createMouseParticle,
    createFolderRippleEffect,
    createCardSubtleEffect,
    createRandomSparkle,
    initDynamicEffects,
    cleanupDynamicEffects
};